package com.ruoyi.binding.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.binding.domain.JDP.Params.*;
import com.ruoyi.binding.domain.MhBinding;
import com.ruoyi.binding.domain.JDP.Tools.OkHttpSessionClient;
import com.ruoyi.binding.service.IMhBindingService;
import com.ruoyi.binding.service.IMhJDPService;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.*;

@Slf4j
@Service
public class MhJDPServiceImpl implements IMhJDPService {

    @Autowired
    private OkHttpSessionClient proSessionClient;

    @Autowired
    private OkHttpSessionClient cusSessionClient;

    @Autowired
    private IMhBindingService mhBindingService;

    private String ProBaseUrl;
    private String CusBaseUrl;



    @PostConstruct
    public void init() {
        proSessionClient.setReloginCallback(this::loginSilently);
        cusSessionClient.setReloginCallback(this::loginSilently);
    }

    private void loginSilently() {
        try {
            this.login();
        } catch (Exception e) {
            log.error("自动重登录失败", e);
        }
    }

    private JSONObject safeResponseBody(Response response) throws IOException {
        if (response != null && response.isSuccessful()) {
            if (response.body() != null) {
                return JSON.parseObject(response.body().string());
            } else {
                return new JSONObject().fluentPut("code", 0).fluentPut("msg", "响应体为空");
            }
        } else {
            return new JSONObject().fluentPut("code", 0)
                    .fluentPut("msg", "请求失败，HTTP状态码：" + (response != null ? response.code() : "null"));
        }
    }

    private synchronized void ensureLoginReady() {
        if (CusBaseUrl == null || ProBaseUrl == null) {
            log.info("未登录或登录信息已失效，正在执行自动登录...");
            JSONObject loginResp = login();
            log.info("自动登录结果：{}", loginResp);
        }
    }

    private final InheritableThreadLocal<Long> userIdHolder = new InheritableThreadLocal<>();

    public void clearUserId() {
        userIdHolder.remove();
    }
    @Override
    public void setUserId(Long userId) {
        userIdHolder.set(userId);
    }


    @Override
    public JSONObject login() {
        try {
            Long userId = userIdHolder.get();
            log.info("本地线程用户ID：{}", userId);
            if (userId == null) {
                userId = SecurityUtils.getUserId(); // HTTP请求中继续支持
            }
            log.info("用户ID：{}", userId);
            MhBinding query = new MhBinding();
            query.setUserId(userId);

            log.info("查询前账号返回参数：{}", query);
            MhBinding binding = mhBindingService.selectMhBindingByUserId(userId);
            log.info("查询后账号返回参数：{}", binding);
            if (binding == null) {
                return new JSONObject().fluentPut("code", 0).fluentPut("msg", "未找到绑定账号");
            }
            log.info("查询绑定账号：{}", query);

            ProBaseUrl = binding.getSupplierAddress();
            CusBaseUrl = binding.getClientAddress();

            Map<String, String> proFormData = Map.of(
                    "acc", binding.getSupplierUsername(),
                    "pwd", binding.getSupplierPassword()
            );

            Map<String, String> cusFormData = Map.of(
                    "acc", binding.getClientUsername(),
                    "pwd", binding.getClientPassword()
            );

            Response proResp = proSessionClient.postForm(ProBaseUrl + Login, proFormData);
            Response cusResp = cusSessionClient.postForm(CusBaseUrl + Login, cusFormData);

            JSONObject proJson = safeResponseBody(proResp);
            JSONObject cusJson = safeResponseBody(cusResp);

            return new JSONObject()
                    .fluentPut("code", 1)
                    .fluentPut("msg", "登录成功")
                    .fluentPut("pro", proJson)
                    .fluentPut("cus", cusJson);

        } catch (Exception e) {
            log.error("登录异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "登录异常：" + e.getMessage());
        }
    }

    @Override
    public JSONObject login(Long deptId, String url, String username, String password) {
        return null;
    }

    @Override
    public JSONObject queryGameType() {
        try {
            ensureLoginReady();
            String url = CusBaseUrl + GetGameServerMangeList;
            Response response = cusSessionClient.get(url, Map.of());
            return safeResponseBody(response);
        } catch (Exception e) {
            log.error("查询游戏类型异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "查询游戏类型异常：" + e.getMessage());
        }
    }

    @Override
    public JSONObject queryInsideRecOrder(JDPProOrderParam param) {
        try {
            ensureLoginReady();
            String url = ProBaseUrl + GetInsideRecOrderList;
            JSONArray allOrders = new JSONArray();
            //由于上家api限制 每次只能查询20条数据 且每次查询间隔不能小于2秒 所以需要分页查询
            int page = param.getPage();
            while (true) {
                Map<String, String> q = new HashMap<>();
                if (param.getGameName() != null) q.put("gameName", param.getGameName());
                q.put("page", String.valueOf(page));
                q.put("limit", String.valueOf(param.getLimit()));
                q.put("key", param.getKey());
                q.put("project", param.getProject());
                log.info("查询抢单大厅订单参数：{}", q);
                log.info("查询抢单大厅订单url：{}", url);
                Response response = proSessionClient.get(url, q);
                JSONObject responseJson = safeResponseBody(response);

                JSONArray orders = responseJson.getJSONArray("data");
                if (orders == null || orders.isEmpty()) {
                    log.info("{} 第{}页 无订单，分页查询结束。", param.getGameName(), page);
                    break;
                }
                for (int i = 0; i < orders.size(); i++) {
                    allOrders.add(orders.getJSONObject(i));
                }
                log.info("{} 第{}页 获取 {} 条订单", param.getGameName(), page, orders.size());
                page++;
                Thread.sleep(1500); // 2秒间隔
            }
            log.info("所有游戏订单总数：{}", allOrders.size());
            return new JSONObject().fluentPut("code", 1)
                    .fluentPut("msg", "查询成功")
                    .fluentPut("total", allOrders.size())
                    .fluentPut("data", allOrders);
        } catch (Exception e) {
            log.error("抢单大厅订单查询异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "抢单大厅订单查询异常：" + e.getMessage());
        }
    }

    @Override
    public JSONObject takeOrder(JDPProTakeOrderParam param) {
        try {
            ensureLoginReady();
            String url = ProBaseUrl + RecOrderSliderVerifiCode;
            Map<String, String> formData = Map.of("id", param.getId());
            Response response = proSessionClient.postForm(url, formData);
            return safeResponseBody(response);
        } catch (Exception e) {
            log.error("抢单异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "抢单异常：" + e.getMessage());
        }
    }

    @Override
    public JSONObject queryOrder(JDPCusQueryOrderParam param) {
        try {
            ensureLoginReady();
            String url = CusBaseUrl + GetOrderList;
            Map<String, String> q = new HashMap<>();
            if (param.getGameName() != null) q.put("gameName", param.getGameName());
            q.put("Key1", param.getKey1());
            q.put("page", String.valueOf(param.getPage()));
            q.put("limit", String.valueOf(param.getLimit()));
            log.info("查询参数{}",q);
            Response response = cusSessionClient.postForm(url, q);
            return safeResponseBody(response);
        } catch (Exception e) {
            log.error("订单查询异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "订单查询异常：" + e.getMessage());
        }
    }

    @Override
    public JSONObject queryUserList() {
        try {
            ensureLoginReady();
            String url = CusBaseUrl + GetUserList;
            Response response = cusSessionClient.get(url, Map.of());
            return safeResponseBody(response);
        } catch (Exception e) {
            log.error("查询用户列表异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "查询用户列表异常：" + e.getMessage());
        }
    }

    @Override
    public JSONObject allocate(JDPCusAllocateParam param) {
        try {
            ensureLoginReady();
            String url = CusBaseUrl + SetOrderZhiPaiByIDX;
            Map<String, String> formData = new HashMap<>();
                    formData.put("orderId", param.getOrderId());
            String strParameterJson = JSON.toJSONString(param.getStrParameter());
            formData.put("strParameter", strParameterJson);
                    formData.put("isAutoAss", param.getIsAutoAss());
                    formData.put("isOpenThrowOrderPricePerce", param.getIsOpenThrowOrderPricePerce());
                    formData.put("taskNeedJobId", param.getTaskNeedJobId());
            Response response = cusSessionClient.postForm(url, formData);
//            打印参数
            log.info("订单指派参数：{}", formData);

            return safeResponseBody(response);
        } catch (Exception e) {
            log.error("订单指派异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "订单指派异常：" + e.getMessage());
        }
    }

    @Override
    public JSONObject setUser(JDPCusSetUserParam param) {
        try {
            ensureLoginReady();
            String url = CusBaseUrl + SetOrderJiWei;
            Map<String, String> formData = Map.of(
                    "orderId", param.getOrderId(),
                    "jiwei", param.getJiwei()
            );
            Response response = cusSessionClient.postForm(url, formData);
            return safeResponseBody(response);
        } catch (Exception e) {
            log.error("机位设置异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "机位设置异常：" + e.getMessage());
        }
    }

    //    修改订单状态为代练中
    @Override
    public JSONObject updateOrderStatus(JDPSetOrderStaParam param) {
        try {
            ensureLoginReady();
            String url = CusBaseUrl + UpdateOrderStatus;
            Map<String, String> formData = Map.of(
                    "orderId", param.getOrderId(),
                    "sta", param.getSta(),
                    "changeSoureType",param.getChangeSoureType(),
                    "isSyncTaoBao", param.getIsSyncTaoBao()
            );
            Response response = cusSessionClient.postForm(url, formData);
            return safeResponseBody(response);
        } catch (IOException e) {
            log.error("修改订单状态异常", e);
            return new JSONObject().fluentPut("code", 0).fluentPut("msg", "修改订单状态异常：" + e.getMessage());
        }
    }
}
